package org.smile.jstl.tags.sql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.smile.db.DbManager;
import org.smile.db.DbUtils;
/**
 * 查询标签
 * @author strive
 *
 */
public class QueryTag extends TagSupport {
	/**
	 * 结果变量
	 */
	private String var="list";
	/**
	 * 查询语句
	 */
	private String sql;
	/**
	 * 参数
	 */
	private Object[] params;
	/**
	 * 数据源名称
	 */
	private String dataSourceName;
	
	private Object oldValue;
	@Override
	public int doEndTag() throws JspException {
		if(oldValue==null){
			pageContext.removeAttribute(var);
			
		}else{
			pageContext.setAttribute(var,oldValue);
		}
		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {
		oldValue=pageContext.getAttribute(var);
		Connection conn;
		if(dataSourceName!=null){
		   conn=DbManager.getConnection(dataSourceName);
		}else{
			conn=DbManager.getConnection();
		}
		try {
			List list=DbUtils.query(conn,sql,params);
			pageContext.setAttribute(var, list);
		} catch (SQLException e) {
			throw new JspException("sql tag query sql cased a exception :",e);
		}
		return EVAL_BODY_INCLUDE;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public Object[] getParams() {
		return params;
	}

	public void setParams(Object[] params) {
		this.params = params;
	}

	public String getDataSourceName() {
		return dataSourceName;
	}

	public void setDataSourceName(String dataSourceName) {
		this.dataSourceName = dataSourceName;
	}
}
